﻿"""
各工站测量数据上传系统
"""
# 导入系统模块
import os
import uuid
from datetime import datetime
from flask import Flask, render_template, url_for, session, request, redirect
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, Length
from flask_wtf.file import FileField, FileRequired, FileAllowed

# 导入自制模块
from csvtosql import csv_read, csv_read_2
from upload import upload_csv, get_moid_info, get_mo_list
from weblog import get_logger

# 初始化日志功能，启动日志记录
logger = get_logger(__name__)
# logger.info("....")

# Flask实例化，加密Cookie
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'secret string')
# 删除Jinja2语句中的空格和制表符
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
# 上传附件最大10Mb上限
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024

# 本机测试：192.168.3.247
ip_dict = {'127.0.0.1': 1, '192.168.20.45': 2, '192.168.20.11': 3, '192.168.20.179': 4}


# 定义工单下载输入界面表单类，设置相关验证要求
class Form1(FlaskForm):
    item_code = StringField('工单号', validators=[DataRequired(), Length(13, 13)])
    user_id = StringField('工号', validators=[DataRequired(), Length(5, 5)])
    # 备注不做验证
    glue = StringField('备注信息（选填）', )
    excel_data = FileField('附件', validators=[FileRequired(), FileAllowed(['xls', 'csv', 'xlsx'])])
    notes = SelectField('测试数据类型', choices=[('固晶推力', '固晶推力'), ('焊线拉力', '焊线拉力'), ('焊线推力', '焊线推力')],
                        validators=[DataRequired()])
    submit = SubmitField('提交')


# 定义文件修改函数


def alter_filename(moid, filename):
    ext = os.path.splitext(filename)[1]
    new_filename = moid + '_' + uuid.uuid4().hex + ext
    return new_filename


# 注册/data路由和data视图函数
@app.route('/', methods=['GET', 'POST'])
def data():
    machine_ip = request.remote_addr
    if machine_ip not in ip_dict:
        logger.warn(f"{machine_ip}非法访问系统！")
        return redirect(url_for('reject'))

    form1 = Form1()
    # 根据年月份自动创建上传文件目录
    uploadsDir = os.path.join('uploaddata', str(datetime.now().year), str(datetime.now().month),
                              str(datetime.now().day))
    if os.path.exists(uploadsDir):
        pass
    else:
        os.makedirs(uploadsDir)
    app.config['UPLOAD_PATH'] = os.path.join(app.root_path, uploadsDir)

    if form1.validate_on_submit():
        # 获取现有的单号
        mo_list = get_mo_list()
        # 获取上传文件信息
        f = form1.excel_data.data
        logger.info(f"{machine_ip}--上传{form1.notes.data}文件名：{f.filename}")
        # 修改文件名，设置上传文件路径
        # filename = alter_filename(form1.item_code.data, f.filename)
        print(f.filename)
        path1 = os.path.join(app.config['UPLOAD_PATH'], f.filename)
        print(path1)
        # 判断当前文件名是否匹配单号\是否已经上传
        moid = form1.item_code.data
        if moid not in mo_list:
            logger.warn(f"单号不存在于MO_ITEM!")
            return "<p>单号错误,请检查单号是否正确！！</p>" + f'<br><a href="{url_for("data")}">返回</a>'
        elif moid not in f.filename:
            logger.warn(f"文件名不包含单号!!")
            return "<p>单号未被包含在文件名中,请检查！！</p>" + f'<br><a href="{url_for("data")}">返回</a>'
        elif os.path.exists(path1):
            logger.warn(f"重复文件上传!!---操作员:{form1.user_id.data}")
            return "<p>该文件已经上传，请检查是否重复操作！！</p>" + f'<br><a href="{url_for("data")}">返回</a>'
        else:
            # 根据路径保存文件
            f.save(path1)
            # 获取测量数据
            # print(f"勾选数据类型为{form1.notes.data}")
            Wire_diameter, chip_size, DB_glue = get_moid_info(form1.item_code.data)
            if form1.item_code.data.startswith('5101-'):
                list_data, error_row, des_string = csv_read(path1, form1.notes.data, Wire_diameter, chip_size, DB_glue)
            else:
                list_data, error_row, des_string = csv_read_2(path1, form1.notes.data)

            print(des_string)

            if error_row == 0:
                update_state, error_str = upload_csv(des_string, form1.user_id.data, list_data,
                                                     form1.item_code.data,
                                                     form1.glue.data, logger)
                if update_state:
                    logger.info(f'{form1.notes.data}数据提交成功!存储名:{path1}')
                    return "<p>数据提交成功</p>" + f'<br><a href="{url_for("data")}">返回</a>'
                else:
                    os.remove(path1)
                    logger.warn(f"{machine_ip}--{form1.notes.data}数据写入数据库失败！！")
                    return f"<p>{error_str}</p>" + f'<br><a href="{url_for("data")}">返回</a>'
            else:
                os.remove(path1)
                logger.warn(f"{machine_ip}--上传数据发生异常！-- {des_string}")
                return f"<p>{des_string}</p>" + f'<br><a href="{url_for("data")}">返回</a>'

    return render_template('stddata.html', form1=form1)


# 注册/reject路由和reject视图函数
@app.route('/reject', methods=['GET'])
def reject():
    return render_template('reject.html')


# 主程序入口
if __name__ == '__main__':
    app.run(debug=True)
